package com.yonyou.brigade.third_parties.zteitc.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.zteitc.constants.ZteitcConstants;
import com.yonyou.brigade.third_parties.zteitc.model.ZteUser;
import com.yonyou.brigade.third_parties.zteitc.service.IZteitcPublicService;
import com.yonyou.brigade.third_parties.zteitc.util.Md5Encrypt;
import com.yonyou.brigade.third_parties.zteitc.util.RestTemplateUtil;
import com.yonyou.ybzboot.starter.common.exception.BaseException;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.util.DateUtils;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/12/24.
 */
@Service
public class ZteitcPublicServiceImpl implements IZteitcPublicService {
    private static final Logger logger = LoggerFactory.getLogger(ZteitcPublicServiceImpl.class);

    @Value("${zteitc.baseUrl}")
    private String baseUrl;

    @Value("${zteitc.ssoUrl}")
    private String ssoUrl;

    @Value("${zteitc.findBillUrl}")
    String findBillUrl;

    @Value("${zteitc.getAccountingDepartmentByOrgUrl}")
    String getAccountingDepartmentByOrgUrl;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Override
    public String ssoLogin(ZteUser zteUser, String type, JSONObject configJSON) {
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String secret = Md5Encrypt.MD5Encode(configJSON.getString("userName") + ZteitcConstants.METHOD_SSO + configJSON.getString("appKey") + timestamp, "UTF-8").toUpperCase();
        // 参数
        JSONObject params = new JSONObject();
        params.put("userName", configJSON.getString("userName"));
        params.put("method", ZteitcConstants.METHOD_SSO);
        params.put("format", "json");
        params.put("currentTime", timestamp);
        params.put("password", secret);
        params.put("data", zteUser.getEmployeeNumber());
        String content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
        JSONObject json = JSONObject.parseObject(content);
        int code = json.getIntValue("code");
        if (code == 500) {
            if (json.getString("message").contains("用户不存在")) {
                return null;
            }
            // 失败
            System.out.println("失败：" + json.getString("message"));
        }
        String authenticationCode = json.getString("data");
        String pwd = Md5Encrypt.MD5Encode(configJSON.getString("userName") + zteUser.getEmployeeNumber() + authenticationCode + configJSON.getString("appKey"), "UTF-8")
                .toUpperCase();
        // -----------------------------------预订单点接口，地址生产后直接拷贝到浏览器可登陆---------------------------------------
        // 国内机票
        String url = ssoUrl + "?callDirect=ssoSrv&pwd=" + pwd + "&authCode=" + authenticationCode;
        if (!StringUtil.isEmpty(type)) {
            url += ("&businessType=" + type);
        }
        url += "&errandType=1";
        return url;
    }

    @Override
    public JSONObject createUser(String tenant, String org, ZteUser zteUser) {
        BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, org, "zteitc");
        if (briChannel == null) {
            throw new BaseException(-100, "当前组织未开通中兴商旅");
        }
        if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
            JSONObject configJSON = JSONObject.parseObject(briChannel.getConfig());
            JSONObject params = getParamByMethod(ZteitcConstants.METHOD_SYNC_EMPLOYEE, configJSON);
            JSONArray employees = new JSONArray();
            employees.add(buildEmployee(zteUser));
            params.put("data", employees.toString());
            String content = "";
            String error = "";
            try {
                content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
                logger.info(content);
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            //记录同步到中兴的用户
            try {
                JSONObject asycResult = JSONObject.parseObject(content);
                JSONArray jsonArray = asycResult.getJSONArray("data");
                if (jsonArray != null && jsonArray.size() > 0) {
                    JSONObject cur = jsonArray.getJSONObject(0);
                    return cur;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /*
        同步人员
     */
    @Override
    public synchronized void syncZteitcSingleUserByPhone(List<ZteUser> zteUsers, BriChannel briChannel) {
        JSONObject configJSON = JSONObject.parseObject(briChannel.getConfig());
        JSONObject params = getParamByMethod(ZteitcConstants.METHOD_SYNC_EMPLOYEE, configJSON);
        JSONArray employees = new JSONArray();
        zteUsers.forEach(
                zteUser -> employees.add(buildEmployee(zteUser))
        );
        params.put("data", employees.toString());
        String content = "";
        String errorms = "";
        try {
            //中兴商旅人员同步接口调用
            content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
            {
                //用户人员同步前需要同步部门信息
                JSONObject syncres = JSONObject.parseObject(content);
                if(syncres!=null && syncres.getInteger("code")==500 && (syncres.getString("message")!=null &&syncres.getString("message").contains("请先同步部门"))){
//                  syncDepatement(briChannel ,param);
                    JSONObject configJSONDep = JSONObject.parseObject(briChannel.getConfig());
                    JSONObject paramsDep = getParamByMethod(ZteitcConstants.METHOD_SYNC_DEPT, configJSONDep);
                    JSONArray data = new JSONArray();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("deptCode", zteUsers.get(0).getDeptCode());
                    jsonObject.put("deptName", zteUsers.get(0).getDeptName());
                    jsonObject.put("enabledFlag", "Y");
                    data.add(jsonObject);
                    paramsDep.put("data", data);
                    String contentDep = RestTemplateUtil.getInstance().postForObject(baseUrl, paramsDep.toString(), String.class);
                    JSONObject result = JSONObject.parseObject(contentDep);
                    if (result == null || !"200".equals(result.getString("code"))) {
                        String errormsg = String.format("同步部门出错! error message:%s", JSON.toJSONString(result));
                        logger.info(errormsg);
                        throw new RuntimeException(errormsg);
                    }
                    //同步完部门后再同步一次人员
                    content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
                }
            }
            logger.info(content);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        JSONObject asycResult = JSONObject.parseObject(content);
        JSONArray jsonArray = asycResult.getJSONArray("data");
        if (jsonArray != null && jsonArray.size() > 0) {
            JSONObject cur = jsonArray.getJSONObject(0);
            if (cur != null && cur.getString("code").equals("200")) {
                return;
            }
        }

        errorms = String.format("同步人员出错! error message:%s", JSON.toJSONString(content));
        logger.info(errorms);
        throw new RuntimeException(errorms);
    }

    @Override
    public JSONObject findOrdersByMethod(String tenant, String orgpk, String startDate, String endDate, String method) {

        JSONObject data = new JSONObject();
        data.put("lastUpdateDateStart", startDate);
        data.put("lastUpdateDateEnd", endDate);
        JSONObject result = execByMethod(tenant, orgpk, data, method,baseUrl);
        return result;
    }

    @Override
    public JSONArray findStatements(String tenant, String orgpk, String periodName) {
        JSONObject data = new JSONObject();
        data.put("periodName", periodName);
        JSONObject result = execByMethod(tenant, orgpk, data, ZteitcConstants.METHOD_FIND_BILL,findBillUrl);
        if (result!=null && "200".equals(result.getString("code"))){
            return result.getJSONArray("data");
        }else {
            return null;
        }
    }

    @Override
    public JSONArray findStatementsDetail(String tenant, String orgpk, String billNum) {
        JSONObject data = new JSONObject();
        data.put("billNum", billNum);
        JSONObject result = execByMethod(tenant, orgpk, data, ZteitcConstants.METHOD_FIND_BILL_ORDER,findBillUrl);
        if (result!=null && "200".equals(result.getString("code"))){
            return result.getJSONArray("data");
        }else {
            return null;
        }
    }
//    @Override
//    public Object syncDepatement(BriChannel briChannel , JSONObject param){
//        try {
//            String result = HttpClientUtil.doPostJson(getAccountingDepartmentByOrgUrl, param.toJSONString());
//            JSONArray depatementArr = JSONArray.parseArray(result);
//            syncZteitcDepartment(depatementArr, briChannel);
//            logger.info("批量同步一级部门成功。" + depatementArr.toJSONString());
//            return ResultUtils.generateSuccessResult("批量同步一级部门成功");
//        } catch (Exception e) {
//            logger.error("批量同步一级部门失败");
//            return ResultUtils.generateErrorResult("批量同步一级部门失败");
//        }
//    }
//
//    @Override
//    public synchronized void syncZteitcDepartment(JSONArray depatementArr, BriChannel briChannel) {
//        JSONObject configJSON = JSONObject.parseObject(briChannel.getConfig());
//        JSONObject params = getParamByMethod(ZteitcConstants.METHOD_SYNC_DEPT, configJSON);
//        JSONArray data = new JSONArray();
//        for (int i = 0; i < depatementArr.size(); i++) {
//            JSONObject depatement = depatementArr.getJSONObject(i);
//            if ("1".equals(depatement.getString("DR"))) {
//                continue;
//            }
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("deptCode", depatement.getString("PK_DEPT"));
//            jsonObject.put("deptName", depatement.getString("NAME"));
//            jsonObject.put("enabledFlag", "Y");
//            data.add(jsonObject);
//        }
//        params.put("data", data);
//        String content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
//        JSONObject result = JSONObject.parseObject(content);
//        if (result == null || !"200".equals(result.getString("code"))) {
//            String errorms = String.format("同步部门出错! error message:%s", JSON.toJSONString(result));
//            logger.info(errorms);
//            throw new RuntimeException(errorms);
//        }
//    }

    /**
     * 通过方法名访问中兴接口
     *
     * @param tenant
     * @param orgpk
     * @param data
     * @param method
     * @return
     */
    private JSONObject execByMethod(String tenant, String orgpk, JSONObject data, String method,String url) {
        BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, orgpk, "zteitc");
        if (briChannel == null) {
            throw new BaseException(-100, "当前组织未开通中兴商旅");
        }
        JSONObject configJSON = JSONObject.parseObject(briChannel.getConfig());
        JSONObject params = getParamByMethod(method, configJSON);
        params.put("data", data);
        //
        String content = RestTemplateUtil.getInstance().postForObject(url, params.toString(), String.class);
        //
        logger.info("zteitc pull orders result:" + content);
        return JSONObject.parseObject(content);
    }

    /**
     * 私有方法
     */
    private static JSONObject buildEmployee(ZteUser zteUser) {
        JSONObject employee = new JSONObject();
        employee.put("enabledFlag", zteUser.getEnabledFlag());
        employee.put("employeeNumber", zteUser.getEmployeeNumber());
        employee.put("employeeName", zteUser.getEmployeeName());
        employee.put("mobilePhone", zteUser.getMobilePhone());
        employee.put("user_property1", zteUser.getUserProperty1());
        employee.put("deptCode",zteUser.getDeptCode());
        return employee;
    }

    private static JSONObject buildIdentity(String cardType, String ownerName, String cardNum, String invalidDate) {
        JSONObject identity = new JSONObject();
        identity.put("cardType", cardType);
        identity.put("ownerName", ownerName);
        identity.put("cardNum", cardNum);
        identity.put("invalidDate", invalidDate);
        return identity;
    }

    private static JSONObject getParamByMethod(String method, JSONObject configJSON) {
        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String secret = Md5Encrypt.MD5Encode(configJSON.get("userName") + method + configJSON.getString("appKey") + timestamp, "UTF-8").toUpperCase();
        JSONObject params = new JSONObject();
        params.put("userName", configJSON.get("userName"));
        params.put("method", method);
        params.put("format", "json");
        params.put("currentTime", timestamp);
        params.put("password", secret);
        return params;
    }

    @Override
    public JSONObject pushApplyOrder(BriChannel channel, String tenant, String orgPk, JSONObject applyOrderJson) {
        JSONObject summaryResult = new JSONObject();
        logger.info("中兴申请单信息:" + applyOrderJson.toString());
        logger.info("开始拼装同步申请单数据");
        String config = channel.getConfig();
        JSONObject data = processApplyData(applyOrderJson, tenant, channel);
        if (data.getString("msg") != null && !"".equals(data.getString("msg"))) {
            summaryResult.put("success", false);
            summaryResult.put("msg", data.getString("msg"));
            return summaryResult;
        }
        JSONObject params = getParamByMethod(ZteitcConstants.METHOD_CREATE_BILL, JSONObject.parseObject(config));
        params.put("data", data);
        logger.info("中兴商旅同步出差申请单，请求数据=" + params.toString());
        String content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
        logger.info("中兴商旅同步出差申请单，返回数据=" + content);
        JSONObject respJSON = JSONObject.parseObject(content);
        if (respJSON != null && respJSON.getInteger("code").intValue() == 200) {
            JSONObject dataJson = respJSON.getJSONObject("data");
            String billNum = dataJson.getString("billNum");
            logger.info("中兴商旅返回的单据号为: " + billNum);
            summaryResult.put("success", true);
            summaryResult.put("msg", "中兴商旅返回的单据号为: " + billNum);

        } else {
            summaryResult.put("success", false);
            summaryResult.put("msg", "中兴商旅申请单同步失败. " + content);
        }
        return summaryResult;
    }

    @Override
    public List closeApplyOrder(String applicationNumber, BriChannel channel) {
        String channelConfig = channel.getConfig();
        JSONArray result = new JSONArray();
        JSONObject params = getParamByMethod(ZteitcConstants.METHOD_CLOSE_BILL, JSONObject.parseObject(channelConfig));
        JSONObject data = new JSONObject();
        data.put("errandBillNum",applicationNumber);
        params.put("data",data);
        logger.info("中兴商旅关闭出差申请单，请求数据=" + params.toString());
        String content = RestTemplateUtil.getInstance().postForObject(baseUrl, params.toString(), String.class);
        logger.info("中兴商旅关闭出差申请单，返回数据=" + content);
        JSONObject respJSON = JSONObject.parseObject(content);
        if (respJSON != null && respJSON.getInteger("code").intValue() != 200) {
            respJSON.put("success",false);
            logger.error("中兴商旅关闭申请单失败"+respJSON.getString("message"));
        }
        respJSON.put("success",true);
        result.add(respJSON);
        return result;
    }

    private JSONObject processApplyData(JSONObject applyOrderJson, String tenant, BriChannel channel) {
        JSONObject applyData = new JSONObject();
        JSONObject config = JSONObject.parseObject(channel.getConfig());
        Integer hotelStrategy = config.getIntValue("hotelStrategy");

        JSONObject special = applyOrderJson.getJSONObject("special");
        String openType = special.getString("openType");
        // 员工ID
        String userId = applyOrderJson.getString("userId");
        List<String> userIdList = new ArrayList<>();
        userIdList.add(userId);
        List<UcUserDto> users = iUserCenterService.getCompleteUcUserDtoByUserid(userIdList, tenant);
        if (users.size() > 0) {
            applyData.put("applyEmpNum", users.get(0).getPersonCode());
            applyData.put("errandEmpNum", users.get(0).getPersonCode());
        } else {
            applyData.put("msg", "找不到用户:" + userId);
            return applyData;
        }
        // 固定值-随便填写
        applyData.put("sourceType", "SQ");
        applyData.put("sourceKey", special.getString("applayNumber"));
        // INLAND/ OVERSEAS：国内/国际
        applyData.put("journeyType", "INLAND");
        applyData.put("reason", "出差");
        applyData.put("isCanModify", "modify");

        //出行人信息
        JSONArray companionInfos = new JSONArray();
        getPassenger(companionInfos, applyOrderJson, tenant,users.get(0).getPersonCode(), openType, channel);
        if (companionInfos.size() > 0 ){
            applyData.put("companionInfos", companionInfos);
        }

        // 行程
        JSONArray travelList = applyOrderJson.getJSONArray("nodeBusinessTravelList");
        JSONArray journeyInfos = new JSONArray();
        JSONArray hotelArray = new JSONArray();
        int seqNum = 0;
        if (hotelStrategy == 1) {
            /*酷开网络 gztx1qwa 的新申请单入住城市传参逻辑（表体上不添加入住城市自定义项）：
                1、交通工具选择后，出租车、公交车、城市地铁三种起始地手工收入，无法明确目的地城市位置，传中兴商旅酒店申请单上，城市不限（不传参即为不限）
                2、其余交通工具都能明确目的地所在城市（往返时，出发地和目的地都记为目的地城市），允许城市范围是一个城市集合
                3、所有行程明细中都能匹配到城市，则进行可入住城市限定
                4、有任何一个行程明细不能匹配到目的地城市（交通工具选择了出租车、公交车、地铁），则本申请单入住城市不限*/
            if (!CollectionUtils.isEmpty(travelList)) {
                boolean controlCity = true;
                for (int i = 0; i < travelList.size(); i++) {
                    JSONObject travel = travelList.getJSONObject(i);
                    String tripWay = travel.getString("tripWay");
                    if ("飞机".equals(tripWay) || "火车".equals(tripWay) || "长途巴士".equals(tripWay) || "轮船".equals(tripWay) || "商务车".equals(tripWay) || "其他".equals(tripWay)) {
                        if ("飞机".equals(tripWay) || "火车".equals(tripWay)) {
                            JSONObject journeyInfo1 = new JSONObject();
                            journeyInfo1.put("seqNo", seqNum++);
                            journeyInfo1.put("trafficTool", "飞机".equals(tripWay) ? "plane" : "train");
                            journeyInfo1.put("fromCity", travel.getString("fromCity").split("-")[0]);
                            journeyInfo1.put("toCity", travel.getString("toCity").split("-")[0]);
                            journeyInfo1.put("startDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("startDate")));
                            journeyInfo1.put("endDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("endDate")));
                            journeyInfos.add(journeyInfo1);
                            if (null != travel.getString("tripType") && "RT".equals(travel.getString("tripType"))) {
                                JSONObject journeyInfo3 = new JSONObject();
                                journeyInfo3.put("seqNo", seqNum++);
                                journeyInfo3.put("trafficTool", "飞机".equals(tripWay) ? "plane" : "train");
                                journeyInfo3.put("fromCity", travel.getString("toCity").split("-")[0]);
                                journeyInfo3.put("toCity", travel.getString("fromCity").split("-")[0]);
                                journeyInfo3.put("startDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("startDate")));
                                journeyInfo3.put("endDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("endDate")));
                                journeyInfos.add(journeyInfo3);
                            }
                        } else {
                            //如果不是机票，火车，则按照酒店传
                            // 住宿信息
                            JSONObject journeyInfo2 = new JSONObject();
                            journeyInfo2.put("seqNo", seqNum++);
                            journeyInfo2.put("trafficTool", "hotel");

                            journeyInfo2.put("startDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("startDate")));
                            journeyInfo2.put("endDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("endDate")));

                            String fcity = travel.getString("fromCity").split("-")[0];
                            String tcity = travel.getString("toCity").split("-")[0];
                            journeyInfos.add(journeyInfo2);
                            if (null != travel.getString("tripType") && "RT".equals(travel.getString("tripType"))) {
                                journeyInfo2.put("fromCity", fcity + "," + tcity);
                                journeyInfo2.put("toCity", fcity + "," + tcity);
                            } else {
                                journeyInfo2.put("fromCity", fcity);
                                journeyInfo2.put("toCity", tcity);
                            }
                        }
                    } else {
                        controlCity = false;
                        // 住宿信息
                        JSONObject journeyInfo2 = new JSONObject();
                        journeyInfo2.put("seqNo", seqNum++);
                        journeyInfo2.put("trafficTool", "hotel");
                        journeyInfo2.put("startDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("startDate")));
                        journeyInfo2.put("endDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("endDate")));
                        journeyInfos.add(journeyInfo2);
                    }
                }
                // 有任何一个行程明细不能匹配到目的地城市（交通工具选择了出租车、公交车、地铁），则本申请单入住城市不限
                if (!controlCity) {
                    for (int i = 0; i < journeyInfos.size(); i++) {
                        JSONObject journeyJSON = journeyInfos.getJSONObject(i);
                        if ("hotel".equals(journeyJSON.getString("trafficTool"))) {
                            journeyJSON.remove("fromCity");
                            journeyJSON.remove("toCity");
                        }
                    }
                }

                applyData.put("journeyInfos", journeyInfos);
                applyData.put("airErrandPolicys", special.getJSONArray("airErrandPolicys"));
            }
        } else {
            if (travelList != null && travelList.size() > 0) {
                for (int i = 0; i < travelList.size(); i++) {
                    JSONObject travel = travelList.getJSONObject(i);
                    if ("飞机".equals(travel.getString("tripWay")) || "火车".equals(travel.getString("tripWay"))) {

                        JSONObject journeyInfo1 = new JSONObject();
                        journeyInfo1.put("seqNo", i);
                        journeyInfo1.put("trafficTool", "飞机".equals(travel.getString("tripWay")) ? "plane" : "train");
                        journeyInfo1.put("fromCity", travel.getString("fromCity").split("-")[0]);
                        journeyInfo1.put("toCity", travel.getString("toCity").split("-")[0]);
                        if (null != travel.getString("tripWay") && "RT".equals(travel.getString("tripWay"))) {
                            journeyInfo1.put("journeyType", "RT");
                        } else {
                            journeyInfo1.put("journeyType", "OW");
                        }
                        journeyInfo1.put("startDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("startDate")));
                        journeyInfo1.put("endDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("endDate")));
                        journeyInfos.add(journeyInfo1);

                    }else {
                        //如果不是机票，火车，则按照酒店传
                        JSONObject journeyInfo2 = new JSONObject();
                        journeyInfo2.put("seqNo", i);
                        journeyInfo2.put("trafficTool", "hotel");
                        journeyInfo2.put("fromCity", travel.getString("fromCity").split("-")[0]);
                        journeyInfo2.put("toCity", travel.getString("toCity").split("-")[0]);
                        if (null != travel.getString("tripWay") && "RT".equals(travel.getString("tripWay"))) {
                            journeyInfo2.put("journeyType", "RT");
                        } else {
                            journeyInfo2.put("journeyType", "OW");
                        }
                        journeyInfo2.put("startDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("startDate")));
                        journeyInfo2.put("endDate", DateUtils.dateToyyyyMMdd(applyOrderJson.getDate("endDate")));
                        journeyInfos.add(journeyInfo2);
                    }

                    applyData.put("journeyInfos", journeyInfos);
                    applyData.put("airErrandPolicys", special.getJSONArray("airErrandPolicys"));
                }
            }
        }
        return applyData;
    }

    private boolean getPassenger(JSONArray companionInfos, JSONObject applyOrderJson, String tenant, String personCode, String openType, BriChannel channel) {
        // 报账3.18新增市级出行人字段格式为{pk;pk}
        String actualPedestrian = applyOrderJson.getString("actualPedestrian");

        // 旧的实际出行人为手输格式，支持格式  张三（17934125896），李四（14536897562）
        String companion = applyOrderJson.getString("companion");

        if (StringUtils.isNotBlank(actualPedestrian)){
            actualPedestrian = convertTraveler(actualPedestrian);
            String[] split = actualPedestrian.split(";");
            List<String> personIds = new ArrayList<>();
            for (String str : split) {
                if (str.split(",").length>0){
                    personIds.add(str.split(",")[0]);
                }
            }
            List<UcUserDto> companionUser = null;
            if ("nc".equals(openType)){
                companionUser = iUserCenterService.getCompleteUcUserByPersonIds(personIds,tenant);
            }else {
                companionUser = iUserCenterService.getCompleteUcUserDtoByUserid(personIds,tenant);
            }

            if (companionUser != null && companionUser.size() == personIds.size()){
                for (UcUserDto ucUserDto : companionUser) {
                    JSONObject companionInfo = new JSONObject();
                    companionInfo.put("personnelType","EMPLOYEE");
                    companionInfo.put("empNum", ucUserDto.getPersonCode());
                    companionInfo.put("personnelName",ucUserDto.getUserName());
                    companionInfos.add(companionInfo);
                }
            }else {
                logger.info("用户中心未找到实际出行人:" + personIds.toString());
                //TODO 用户中心未找到人员时同步erp用户，再次查找。
                throw new BusinessException("用户中心未找到部分实际出行人");
            }
        }
        UcUserDto sscUser = iUserCenterService.getCompleteUcUserDtoByPersonCode(personCode, tenant);
        if (StringUtils.isNotBlank(companion) && !companion.equals(sscUser.getUserName())) {
            companion = convertTraveler(companion);
            if (!StringUtils.isEmpty(companion)) {
                String[] split = companion.split(",");
                for (String str : split) {
                    String[] strings = str.split(":");
                    String name = strings[0];
                    JSONObject companionInfo = new JSONObject();
                    companionInfo.put("personnelType","RELATIVE");
                    companionInfo.put("personnelName",name);
                    companionInfos.add(companionInfo);
                }
            }
        }
        if (companionInfos.size() <= 0){
            JSONObject companionInfo = new JSONObject();
            companionInfo.put("personnelType","EMPLOYEE");
            companionInfo.put("empNum", sscUser.getPersonCode());
            companionInfo.put("personnelName",sscUser.getUserName());
            companionInfos.add(companionInfo);
        }

        return true;
    }


    /**
     * 转换companion中的字符
     *
     * @param companion
     * @return
     */
    public static String convertTraveler(String companion) {
        String convertStr = companion;
        if (companion.contains("（")) {
            convertStr = companion.replaceAll("（", ":");
        }
        if (companion.contains("(")) {
            convertStr = convertStr.replaceAll("\\(", ":");
        }
        if (companion.contains("）")) {
            convertStr = convertStr.replaceAll("）", "");
        }
        if (companion.contains(")")) {
            convertStr = convertStr.replaceAll("\\)", "");
        }
        if (companion.contains("，")) {
            convertStr = convertStr.replaceAll("，", ",");
        }
        if (companion.contains("、")) {
            convertStr = convertStr.replaceAll("、", ",");
        }
        return convertStr;
    }

}
